import 'package:get/get.dart';
import 'package:xindong/common/xindong_api_path.dart';
import 'package:xindong/common/xindong_common_vm.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/manager/network/xindong_response.dart';
import 'package:xindong/models/xindong_notice_class.dart';

class XinDongNoticeVM extends XinDongCommonVM {
  static XinDongNoticeVM get to => Get.find();

  // 请求加载列表
  Future<void> requestLoadData(
      {required int yemian, int yemianSize = 20, required Function(NetworkResponse) callback}) async {
    isLoading = true;
    var parameters = {"page": yemian, "pagesize": yemianSize};
    final object = await XinDongNetworking.instance.request(
      XinDongApi.messageList,
      method: XinDongHttpMethod.post,
      parameters: parameters,
    );
    callback(object);
    Future.delayed(const Duration(milliseconds: 1000)).whenComplete(() => isLoading = false);
  }

  List<XinDongNoticeClass> jsonToArrayClass(List result) {
    return result.map((e) => XinDongNoticeClass.fromJson(e)).toList();
  }

  @override
  void refreshData({object}) {
    yemian = 0;
    requestLoadData(
      yemian: 0,
      callback: (object) {
        if (object.code == XinDongServerStatus.success) {
          final list = jsonToArrayClass(object.data);
          hasMore = list.isNotEmpty;
          dataList = list;
        }
        // 最后调用父类方法，执行后续操作
        super.refreshData(object: object);
      },
    );
  }

  @override
  void loadMoreData({object}) {
    if (!hasMore) {
      refreshController.loadNoData();
      return;
    }
    yemian++;
    requestLoadData(
      yemian: yemian,
      callback: (object) {
        if (object.code == XinDongServerStatus.success) {
          final list = jsonToArrayClass(object.data);
          hasMore = list.isNotEmpty;
          dataList!.addAll(list); // 拼接数据
        } else {
          yemian--;
        }
        // 最后调用父类方法，执行后续操作
        super.loadMoreData(object: object);
      },
    );
  }
}
